<script setup lang="ts">
import { nextTick, provide, shallowRef, watch } from 'vue'
import { fromJson } from '../utils'
import { routerState, pushState } from './router'

const props = defineProps(['routes'])
const allPages = shallowRef([])
const page = shallowRef()

provide('allPages', allPages)

const toPage = (pageName) => {
  const pageNode = allPages.value?.find((page) => page.props.name == pageName)

  if (pageNode) page.value = pageNode
}

watch(
  () => props.routes,
  (newValue) => {
    if (typeof newValue == 'string') allPages.value = fromJson(newValue)
    else allPages.value = newValue

    nextTick(() => pushState(allPages.value?.at(0)?.props.name))
  },
  { immediate: true }
)

watch(
  routerState,
  () => {
    toPage(routerState.value.at(-1))
  },
  { deep: true }
)
</script>

<template>
  <component :is="page?.component"></component>
</template>
